//
//  TestGridCollectionViewController.m
//  MKUITestApp
//
//  Created by 苏尚进 on 2020/9/5.
//  Copyright © 2020 moon. All rights reserved.
//

#import "TestGridPageCollectionViewController.h"
#import "Menu.h"
#import "MenuCollectionViewCellModel.h"
#import "MenuCollectionViewCell.h"

@interface TestGridPageCollectionViewController ()<MKUICollectionViewDelegateGridPageLayout>
@property(nonatomic,strong) MKUICollectionViewSectionModel *sm1;//一页只显示一个
@property(nonatomic,strong) MKUICollectionViewSectionModel *sm2;//一页只显示一行，一行显示4个
@property(nonatomic,strong) MKUICollectionViewSectionModel *sm3;//itemsize为75x75
@property(nonatomic,strong) UIPageControl *pageControl;
@end

@implementation TestGridPageCollectionViewController
+ (MKTFuncItem *)funcItem{
    return [MKTFuncItem funcWithName:@"GridPage集合" viewControllerClass:self];
}
- (id)init{
    MKUIGridPageCollectionViewLayout *layout = [[MKUIGridPageCollectionViewLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(5, 10, 15, 20);
    layout.interitemSpacing = 5;
    layout.lineSpacing = 10;
    layout.itemSize = CGSizeMake(100, 100);
    if(self=[super initWithCollectionViewLayout:layout]){
        self.title = [self.class funcItem].name;
    }
    return self;
}
- (void)viewDidLoad{
    [super viewDidLoad];
//    self.collectionView.pagingEnabled = YES;
    self.collectionView.decelerationRate = UIScrollViewDecelerationRateFast;
    self.model.forwardDelegate = self;
    UIBarButtonItem *addItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemAdd) target:self action:@selector(__onAdd)];
    UIBarButtonItem *delItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemTrash) target:self action:@selector(__onDelSection)];
    self.navigationItem.rightBarButtonItems = @[addItem,delItem];
    //
    self.pageControl = [[UIPageControl alloc] init];
    self.pageControl.pageIndicatorTintColor = [UIColor systemGrayColor];
    self.pageControl.currentPageIndicatorTintColor = [UIColor systemBlueColor];
    [self.view addSubview:self.pageControl];
    //
    [self __reloadData];
}
- (void)dealloc{
    self.collectionView.delegate = nil;
}
- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    [self __updatePageControl];
    [self __layoutPageControl];
}
- (void)__updatePageControl{
    MKUIGridPageCollectionViewLayout *layout = self.collectionView.mk_collectionViewGridPageLayout;
    self.pageControl.numberOfPages = layout.numberOfPages;
    self.pageControl.currentPage = layout.currentPage;
}
- (void)__layoutPageControl{
    CGRect bounds = self.view.bounds;
    UIEdgeInsets insets = self.collectionView.mk_adjustedContentInset;
    CGRect f1 = CGRectZero;
    f1.size = [self.pageControl sizeThatFits:bounds.size];
    f1.origin.y = bounds.size.height-insets.bottom-f1.size.height-5;
    f1.origin.x = insets.left+(bounds.size.width-insets.left-insets.right-f1.size.width)*0.5;
    self.pageControl.frame = f1;
}
- (void)__onAdd{
    static NSInteger __index__ = 0;
    NSArray<Menu *> *menus = [Menu sharedMenus];
    MenuCollectionViewCellModel *cm = [self creatCellModelWithMenu:menus[__index__%menus.count]];
    MKUIGridPageCollectionViewLayout *layout =  self.collectionView.mk_collectionViewGridPageLayout;
    NSIndexPath *p = [layout itemIndexPathsForPage:layout.visiblePage].lastObject;
    if(p){
        NSIndexPath *indexpath = [NSIndexPath indexPathForItem:p.item+1 inSection:p.section];
        [self.model insertCellModel:cm atIndexPath:indexpath];
        [self.collectionView performBatchUpdates:^{
            [self.collectionView insertItemsAtIndexPaths:@[indexpath]];
        } completion:nil];
    }else{
        [self.model addCellModel:cm animated:YES completion:nil];
    }
    __index__++;
    [self __updatePageControl];
}
- (void)__onDel{
    MKUIGridPageCollectionViewLayout *layout = self.collectionView.mk_collectionViewGridPageLayout;
    NSInteger pageIndex = layout.currentPage;
    if(pageIndex!=NSNotFound){
        NSIndexPath *indexpath = [layout itemIndexPathsForPage:pageIndex].lastObject;
        if(indexpath){
            MenuCollectionViewCellModel *cm = [self.model cellModelAtIndexPath:indexpath];
            [self.model removeCellModel:cm animated:YES completion:nil];
        }
    }
    [self __updatePageControl];
}
- (void)__onDelSection{
    MKUIGridPageCollectionViewLayout *layout = self.collectionView.mk_collectionViewGridPageLayout;
    NSInteger section = layout.currentSection;
    if(section!=NSNotFound){
        [self.model removeSectionModel:[self.model sectionModelAtIndex:section] animated:YES completion:nil];
    }
    [self __updatePageControl];
}
- (void)__reloadData{
    [self.model removeAllSectionModels];
    
    {
        MKUICollectionViewSectionModel *sm = [[MKUICollectionViewSectionModel alloc] init];
        self.sm2 = sm;
        [self.model addSectionModel:sm];
        for (Menu *m in [[Menu sharedMenus] subarrayWithRange:NSMakeRange(0, 6)]) {
             [self.model addCellModel:[self creatCellModelWithMenu:m]];
        }
    }
    {
        MKUICollectionViewSectionModel *sm = [[MKUICollectionViewSectionModel alloc] init];
        self.sm1 = sm;
        [self.model addSectionModel:sm];
        for (Menu *m in [[Menu sharedMenus] subarrayWithRange:NSMakeRange(0, 3)]) {
             [self.model addCellModel:[self creatCellModelWithMenu:m]];
        }
    }
    {
        MKUICollectionViewSectionModel *sm = [[MKUICollectionViewSectionModel alloc] init];
        self.sm3 = sm;
        [self.model addSectionModel:sm];
        for (int j=0; j<2; j++) {
            for (Menu *m in [Menu sharedMenus]) {
                [self.model addCellModel:[self creatCellModelWithMenu:m]];
            }
        }
    }
    for (int i=0; i<5; i++) {
        MKUICollectionViewSectionModel *sm = [[MKUICollectionViewSectionModel alloc] init];
        [self.model addSectionModel:sm];
        for (int j=0; j<1; j++) {
            for (Menu *m in [Menu sharedMenus]) {
                [self.model addCellModel:[self creatCellModelWithMenu:m]];
            }
        }
    }
    {
        MKUICollectionViewSectionModel *sm = [[MKUICollectionViewSectionModel alloc] init];
        [self.model addSectionModel:sm];
        for (Menu *m in [Menu sharedUrlMenus]) {
             [self.model addCellModel:[self creatCellModelWithMenu:m]];
        }
    }
    [self.model reloadCollectionViewData];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.collectionView.mk_collectionViewGridPageLayout scrollToPage:1 animated:YES];
    });
    [self __updatePageControl];
}
- (MenuCollectionViewCellModel *)creatCellModelWithMenu:(Menu *)m{
    MenuCollectionViewCellModel *cm = [[MenuCollectionViewCellModel alloc] initWithModelObject:m];
    cm.cellClass = [MenuCollectionViewCell class];
    @MK_WEAKIFY(self);
    cm.whenClick = ^(__kindof MKUICollectionViewCellModel * _Nonnull cellModel) {
        @MK_NORMALIZE(self);
        [self.model removeCellModel:cellModel animated:YES completion:nil];
        [self __updatePageControl];
    };
    return cm;
}
#pragma mark - delegate:MKUICollectionViewDelegateGridPageLayout
- (CGSize)collectionView:(UICollectionView *)collectionView gridPageLayout:(MKUIGridPageCollectionViewLayout *)collectionViewLayout itemSizeForSectionAtIndex:(NSInteger)section{
    CGSize itemSize = collectionViewLayout.itemSize;
    MKUICollectionViewSectionModel *sm = [self.model sectionModelAtIndex:section];
    if(sm==self.sm1){
        itemSize = [collectionViewLayout itemSizeThatFitsItemsPerRow:1 lines:1 interitemSpacing:collectionViewLayout.interitemSpacing lineSpacing:collectionViewLayout.lineSpacing sectionInsets:collectionViewLayout.sectionInset];
    }else if(sm==self.sm2){
        itemSize = [collectionViewLayout itemSizeThatFitsItemsPerRow:4 lines:1 interitemSpacing:collectionViewLayout.interitemSpacing lineSpacing:collectionViewLayout.lineSpacing sectionInsets:collectionViewLayout.sectionInset];
    }else if(sm==self.sm3){
        itemSize = CGSizeMake(75, 75);
    }
    return itemSize;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView gridPageLayout:(MKUIGridPageCollectionViewLayout *)collectionViewLayout lineSpacingForSectionAtIndex:(NSInteger)section{
    return [collectionViewLayout lineSpacingThatFitsItemSize:[collectionViewLayout itemSizeForSectionAtIndex:section] minimumLineSpacing:collectionViewLayout.lineSpacing sectionInsets:collectionViewLayout.sectionInset];
}
- (CGFloat)collectionView:(UICollectionView *)collectionView gridPageLayout:(MKUIGridPageCollectionViewLayout *)collectionViewLayout interitemSpacingForSectionAtIndex:(NSInteger)section{
    return [collectionViewLayout interitemSpacingThatFitsItemSize:[collectionViewLayout itemSizeForSectionAtIndex:section] minimumInteritemSpacing:collectionViewLayout.interitemSpacing sectionInsets:collectionViewLayout.sectionInset];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    MKUIGridPageCollectionViewLayout *layout = self.collectionView.mk_collectionViewGridPageLayout;
//    NSInteger page = layout.currentPage;
//    NSInteger count = layout.numberOfPages;
//    NSInteger fromPage = 0;
//    NSInteger toPage = 0;
//    CGFloat progress = [layout scrollProgressWithContentOffset:scrollView.contentOffset fromPage:&fromPage toPage:&toPage];
//    NSLog(@"progress:%@/%@,scroll %@->%@(%.2f)",@(page+1),@(count),@(fromPage),@(toPage),progress);
    [self __updatePageControl];
}
@end
